package com.lyandwc.lw_bbs.security.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyandwc.lw_bbs.entity.User;
import com.lyandwc.lw_bbs.security.entity.UserRole;
import com.lyandwc.lw_bbs.security.service.UserRoleService;
import com.lyandwc.lw_bbs.service.UserService;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Map;

@RestController
@RequestMapping(value = "/register")
public class RegisterController {
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private UserService userService;
    private UserRoleService userRoleService;


    public RegisterController(BCryptPasswordEncoder bCryptPasswordEncoder, UserService userService, UserRoleService userRoleService) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userService = userService;
        this.userRoleService = userRoleService;
    }

    @RequestMapping(method = RequestMethod.POST)
    public JSONObject register(
            @RequestBody Map<String, String> map
    ) {
        String username = map.get("username");
        String password = map.get("password");
        if (userService.findUserByName(username) != null) {
            return ResponseUtils.fail("Duplicate username.");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(bCryptPasswordEncoder.encode(password));
        user.setStatus(0);
        user.setCreateAt(new Timestamp(System.currentTimeMillis()));
        userService.save(user);

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(2);
        userRoleService.save(userRole);

        return ResponseUtils.success(user);
    }
}
